package main

import (
	"cas_data_acquisition/preprocessor"
	"log"
	"time"
)

type extractDataFunction func() []float64
type queueNode = extractDataFunction

// queue 是buffer为1000的channel，用于接受采集卡传过来的数据。如果buffer满了发生阻塞，说明处理数据已经落后了
var queue = make(chan queueNode, 1000)

type sampleDataType struct {
	TimeUnixNano int64
	Data         float64
}

func initQueue() {
	var preProcessor preprocessor.PreProcessor = nil
	if conf.PreProcessor != "" {
		preProcessor = preprocessor.NewPreProcessor(conf.PreProcessor)
	}
	go func() {
		count := 0
		for {
			extractData := <-queue
			data := extractData()
			if preProcessor != nil {
				for i, d := range data {
					data[i] = preProcessor.Process(d)
				}
			}

			count += len(data)
			go func() {
				if err := saveDacSamples(data); err != nil {
					log.Println("保存数据点到数据库失败！错误：", err)
				}
			}()
			if count >= conf.SamplesPerSecond && len(data) > 0 {
				// 每1秒提取出一个值，发送给中心数据服务器
				sampleToSend := sampleDataType{
					TimeUnixNano: time.Now().UnixNano(),
					Data:         data[0],
				}
				if err := saveCentralServerSamples(data[0]); err != nil {
					log.Println("保存数据点到数据库失败！错误：", err)
				}
				sendDataToCentralServer(sampleToSend)
				count -= conf.SamplesPerSecond
			}
		}
	}()
}
